package pages;

import core.TestBase;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import utils.Log4Test;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import static org.testng.AssertJUnit.assertFalse;

public class GeneralPage extends TestBase {





    public void open(String URL)

    {

        webDriver.get(URL);

    }

    public void logOut()

    {
        ((JavascriptExecutor) webDriver).executeScript("arguments[0].click();", elementIsLocated(getLocator("exitButton")));
    }


    protected WebElement elementIsLocated(By element)

    {
        try {
            return wait.until(ExpectedConditions.presenceOfElementLocated(element));
        } catch (StaleElementReferenceException e) {
            return wait.until(ExpectedConditions.presenceOfElementLocated(element));
        } catch (NoSuchElementException ele) {
            return wait.until(ExpectedConditions.presenceOfElementLocated(element));
        }
    }


    public void javaScriptClick(String element)

    {
        ((JavascriptExecutor) webDriver).executeScript("arguments[0].click();", elementIsLocated(getLocator(element)));
    }


    public void waitForPageLoaded(WebDriver driver)

    {

        ExpectedCondition<Boolean> expectation = new
                ExpectedCondition<Boolean>() {
                    public Boolean apply(WebDriver driver) {
                        return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
                    }
                };

        try {
            wait.until(expectation);
        } catch (Throwable error) {
            assertFalse("Timeout waiting for Page Load Request to complete.", true);
        }
    }


    public boolean isElementPresent(String locator) {
        //Set the timeout to something low
        boolean exists = false;
        webDriver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
        try {
            webDriver.findElement(getLocator(locator)).getTagName();
            exists = true;

            //If element is found set the timeout back and return true

        } catch (NoSuchElementException e) {
            //If element isn't found, set the timeout and return false

        }
        webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        return exists;

    }


    public By getLocator(String logicalElementName)

    {
        Properties properties = new Properties();

        try {
            properties.load(GeneralPage.class.getResourceAsStream("/object.map.properties"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        String locator = properties.getProperty(logicalElementName);

        String locatorType = locator.split(">")[0];

        String locatorValue = locator.split(">")[1];

        if (locatorType.toLowerCase().equals("id"))
            return By.id(locatorValue);

        else if ((locatorType.toLowerCase().equals("classname")) ||
                (locatorType.toLowerCase().equals("class")))
            return By.className(locatorValue);

        else if ((locatorType.toLowerCase().equals("cssselector")) ||
                (locatorType.toLowerCase().equals("css")))
            return By.cssSelector(locatorValue);

        else if (locatorType.toLowerCase().equals("xpath"))
            return By.xpath(locatorValue);

        else
            try {
                throw new Exception("Locator type '" + locatorType + "' not defined!!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        return null;
    }


    public LoginPage clickLoginLinkOnTheHeader(){
        Log4Test.info("Click 'Login' link at the header");
        elementIsLocated(getLocator("loginLink")).click();
        return new LoginPage();
    }

    public PostAdPage clickPostAnAdBtnOnTheHeader(){
        Log4Test.info("Click 'Post An Ad' red button at the header");
        elementIsLocated(getLocator("postAnAdButton")).click();
        return new PostAdPage();
    }

    public boolean isTextPresent(String TEXT, String locator) {
        Log4Test.info("Verify that text: \"" + TEXT + "\" is present");
        WebElement text = elementIsLocated(getLocator(locator));
        return text.getText().equals(TEXT);

    }


    public DdlPage hoverDdlAtTheHeader(){
        Log4Test.info("Hover cursor on the DDL at the header");
        Actions actions = new Actions(webDriver);
        actions.moveToElement(elementIsLocated(getLocator("dropDownList"))).build().perform();
        return new DdlPage();


    }


    public int getElementsNumber(String locatorList){
        List<WebElement> ads = webDriver.findElements(getLocator(locatorList));
        int i=0;
        for (WebElement element: ads){
            i++;
        }
        return i;


    }


}
